package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;
    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //设置分页参数
        PageHelper.startPage(currentPage,pageSize);
        Page<Permission> pages= permissionDao.findByCondition(queryString);
        return new PageResult(pages.getTotal(),pages.getResult());
    }
    //添加权限
    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    //根据id查询权限
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }
    //编辑权限
    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }
    //根据id删除权限
    @Override
    public void deleteById(Integer id) {
        //根据权限id查询相关联的角色
       long count =  permissionDao.findroleByPermissionId(id);
        //判断
        if (count > 0) {
            //如果存在,则不能删除
            throw new RuntimeException("您删除的权限已绑定"+count+"个角色,无法删除");
        }
        //不存在
        permissionDao.deleteById(id);
    }
    @Override
    public List<Permission> findAll() {

        return permissionDao.findAll();
    }
}
